#include "command.h"

int _tail(char *argv[])
{
	/* check the number of cmd-line parameters is correct */
	int argc = 0;
	for (char **ptr = argv; *ptr != NULL; ptr++)
		argc++;

	if (argc > 4) {
		fprintf(stderr, "Usage: tail [-n num] file\n");
		return -1;
	}

	int lines_to_read = 10; 
	int opt; 		/* option character */
	const char *opt_fmt = "n:"; /* option format */

	/* parse the cmd-line parameters */
	while ((opt = getopt(argc, argv, opt_fmt)) != -1) {
		switch (opt) {
			case 'n': 
				lines_to_read = atoi(optarg);
				break;
			default:
				fprintf(stderr, "Usage: tail [-n num] file\n");
				return -1;
		}
	}

	/* handle wrong case about lines_to_read */
	if (lines_to_read <= 0) {
		fprintf(stderr, "tail error: option [-n num]--->num must be greater than 0\n");
		return -1;
	}

	/* locate at the end of file and read reversely to determine where to read */
	if (!argv[optind]) {
		fprintf(stderr, "Usage: tail [-n num] file\n");
		return -1;
	}

	const char *file = argv[optind];
	int line_count = 0;

	int fd = open(file, O_RDONLY);
	if (fd == -1) {
		fprintf(stderr, "tail error: open\n");
		return -1;
	}
	
	int offset = lseek(fd, 0, SEEK_END);
	char ch;
	// if we want to read last 5 lines, offset must be at the end of last 6 line
	for (int i = offset - 1; i >= 0 && line_count <= lines_to_read; i--) {
		lseek(fd, i, SEEK_SET);
		read(fd, &ch, 1);
		if (ch == '\n')
			line_count++;
	}
	
	/* read the content to buffer and write to stdout */
	int num_read = 0;
	char buf[BUF_SIZE];
	while ((num_read = read(fd, buf, BUF_SIZE)) > 0) {
		write(STDOUT_FILENO, buf, num_read);
	}

	close(fd);

	if (num_read == -1) {
		fprintf(stderr, "tail error: read\n");
		return -1;
	}

	return 0;
}
